package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author luhan
 * @create 2022/5/21 13:39
 */
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request){

        UserInfo info = userService.login(userInfo);
        if (info!=null){
            // 登录成功 需要生成token，页面需要获取 然后将token放入cookie中 需要userInfo对象数据
            // 生成token
            String token = UUID.randomUUID().toString();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("token",token);
            hashMap.put("nickName",info.getNickName());

            // 判断用户真实登录的依据，把数据放入缓存
            // 确定数据类型和key
            String userKey = RedisConst.USER_LOGIN_KEY_PREFIX + token;
            // 缓存中存储用户id和ip地址
            String ip = IpUtil.getIpAddress(request);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("userId",info.getId().toString());
            jsonObject.put("ip",ip);
            redisTemplate.opsForValue().set(userKey,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

            // 将map中的数据返回给前台页面
            return Result.ok(hashMap);
        } else {
            return Result.fail().message("用户名或密码错误");
        }

    }

    @GetMapping("logout")
    public Result logout(HttpServletRequest request){
        String token = request.getHeader("token");
        // 删除缓存中数据
        redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
        return Result.ok();
    }

}
